﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KMF.Common;
using KMF.DAL;
using KMF.Utility;
using KMF.WebUI.Areas.KMFadmin.Models;
using KMF.WebUI.Areas.KMFadmin.CustomHelpers;
using KMF.WebUI.Areas.KMFadmin.Infrastructure;
using KMF.WebUI.Areas.KMFadmin.Attributes;

namespace KMF.WebUI.Areas.KMFadmin.Controllers
{
    [AdminLoggedAuthorize]
    public class AdminBannerController : Controller
    {
        //
        // GET: /Admin/Banner/
        #region Banner
        public ActionResult Index(int page = 1)
        {
            var itemsPerPage = int.Parse(ConfigurationManager.AppSettings["DefaultItemsPerPage"]);
            var totalPage = 0;
            var totalRecord = 0;
            var model = BannerDb.GetAllBanner(page, itemsPerPage, ref totalPage, ref totalRecord) ?? new List<ViewBannerDto>();

            ViewBag.PageInfo = new PageInfo { CurrentPage = page, PageSize = itemsPerPage, TotalPages = totalPage };
            ViewBag.TotalRecord = totalRecord;
            return View(model);
        }

        public ActionResult SearchBanner(string keyword = "")
        {
            return View();
        }

        public ActionResult AddBanner()
        {
            ViewBag.PageList = PageDb.GetAll() ?? new List<PageDto>();
            ViewBag.PositionList = PositionDb.GetAll() ?? new List<PositionDto>();
            ViewBag.MenuList = FunctionHelper.GetMenuListThreeLevel();
            return View();
        }

        [HttpPost]
        public ActionResult AddBanner(BannerDto model)
        {
            //var bannerList = BannerDb.GetBannerByPageIdPositionId(model.PageId, model.PositionId) ?? new List<BannerDto>();
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("ErrorSummary", "Đã có lỗi xảy ra!");
                ViewBag.PageList = PageDb.GetAll() ?? new List<PageDto>();
                ViewBag.PositionList = PositionDb.GetAll() ?? new List<PositionDto>();
                ViewBag.MenuList = FunctionHelper.GetMenuListThreeLevel();
                return View(model);
            }

            model.BannerId = Utility.Common.GenerateId();
            BannerDb.Add(model);
            return RedirectToAction("EditBanner", "AdminBanner", new { id = model.BannerId });
        }

        public ActionResult EditBanner(string id = "")
        {
            ViewBag.PageList = PageDb.GetAll() ?? new List<PageDto>();
            ViewBag.PositionList = PositionDb.GetAll() ?? new List<PositionDto>();
            ViewBag.MenuList = FunctionHelper.GetMenuListThreeLevel();
            var model = BannerDb.GetById(id) ?? new BannerDto();
            return View(model);
        }

        [HttpPost]
        public ActionResult EditBanner(BannerDto model)
        {            
            BannerDb.Update(model);
            ViewBag.PageList = PageDb.GetAll() ?? new List<PageDto>();
            ViewBag.PositionList = PositionDb.GetAll() ?? new List<PositionDto>();
            ViewBag.MenuList = FunctionHelper.GetMenuListThreeLevel();

            return RedirectToAction("EditBanner", new { id = model.BannerId });
        }

        public JsonResult DeleteBanner(string bannerId)
        {
            BannerDb.Delete(bannerId);

            var bannerImageList = BannerImageDb.GetAllByBannerId(bannerId) ?? new List<BannerImageDto>();
            foreach (var bannerImageDto in bannerImageList)
            {
                ImageHelper.DeleteImageFile(bannerImageDto.ImagePath);
            }

            BannerImageDb.DeleteByBannerId(bannerId);

            return Json(true, JsonRequestBehavior.AllowGet);
        }

        public PartialViewResult UploadBannerImage(string bannerId = "")
        {
            ViewBag.BannerImageList = BannerImageDb.GetAllByBannerId(bannerId) ?? new List<BannerImageDto>();
            ViewBag.BannerId = bannerId;
            return PartialView();
        }

        [HttpPost]
        public WrappedJsonResult UploadBannerImage(BannerImageDto model, HttpPostedFileWrapper imageFile)
        {
            if (imageFile == null || imageFile.ContentLength == 0)
            {
                return new WrappedJsonResult
                {
                    Data = new { IsValid = false, Message = "Bạn cần chọn File ảnh để upload." }
                };
            }
            string error;

            // Create root images
            var imagePath = ImageHelper.UploadImageCommon(out error, ConstParam.FolderUploadBannerImage, imageFile);

            // Insert infomation into bannerImage table
            model.BannerImageId = FunctionHelper.GenerateId();
            model.ImagePath = imagePath;
            model.CreateDate = DateTime.Now;

            var result = BannerImageDb.Add(model);
            if(result > 0)
            {
                return new WrappedJsonResult
                {
                    Data = new { IsValid = true, model.BannerImageId }
                };    
            }

            return new WrappedJsonResult
            {
                Data = new { IsValid = false, Message = "Đã có lỗi xảy ra." }
            };
        }
        
        public PartialViewResult AjaxBannerImageItem(string bannerImageId = "")
        {
            var model = BannerImageDb.GetById(bannerImageId) ?? new BannerImageDto();
            return PartialView(model);
        }

        public JsonResult AjaxDeleteBannerImage(string bannerImageId = "", string imagePath = "")
        {
            ImageHelper.DeleteImageFile(imagePath);
            var result = BannerImageDb.Delete(bannerImageId);
            var data = new {
                               IsValid = result > 0,
                               BannerImageId = bannerImageId
                           };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public PartialViewResult AjaxEditBannerImage(string bannerImageId = "")
        {
            var model = BannerImageDb.GetById(bannerImageId) ?? new BannerImageDto();
            return PartialView(model);
        }

        [HttpPost]
        public WrappedJsonResult AjaxEditBannerImage(BannerImageDto model, HttpPostedFileWrapper imageFile)
        {
            if (imageFile != null)
            {
                string error;
                var imagePath = ImageHelper.UploadImageCommon(out error, ConstParam.FolderUploadBannerImage, imageFile, model.ImagePath);
                if (!string.IsNullOrEmpty(error))
                {
                    return new WrappedJsonResult
                    {
                        Data = new { IsValid = false, Message = "Đã có lỗi xảy ra." }
                    };
                }
                model.ImagePath = imagePath;
            }
            
            model.UpdateDate = DateTime.Now;

            var result = BannerImageDb.Update(model);
            if (result > 0)
            {
                return new WrappedJsonResult
                {
                    Data = new { IsValid = true, model.BannerImageId }
                };
            }

            return new WrappedJsonResult
            {
                Data = new { IsValid = false, Message = "Đã có lỗi xảy ra." }
            };
        }

        #endregion Banner

        #region Page

        public ActionResult PageList()
        {
            var model = PageDb.GetAll() ?? new List<PageDto>();
            return View(model);
        }

        public ActionResult AddPage()
        {
            return View();
        }

        [HttpPost]
        public ActionResult AddPage(PageDto model)
        {
            model.CreateDate = DateTime.Now;
            model.PageKey = StringUtil.RemoveSpecialCharactersVn(model.Name).ToUpper();

            var pageList = PageDb.GetByKey(model.PageKey) ?? new List<PageDto>();
            if (pageList.Any())
            {
                ModelState.AddModelError("ErrorSummary", "Trang này đã tồn tại, bạn cần nhập một tên khác!");
                return View(model);
            }

            var result = PageDb.AddPage(model);
            return RedirectToAction("EditPage", new { id = result });
        }

        public ActionResult EditPage(int id)
        {
            var model = PageDb.GetById(id) ?? new PageDto();
            return View(model);
        }

        [HttpPost]
        public ActionResult EditPage(PageDto model)
        {
            model.PageKey = StringUtil.RemoveSpecialCharactersVn(model.Name).ToUpper();
            var pageList = PageDb.GetByKey(model.PageKey) ?? new List<PageDto>();
            if (pageList.Any())
            {
                ModelState.AddModelError("ErrorSummary", "Trang này đã tồn tại, bạn cần nhập một tên khác!");
                return View(model);
            }

            PageDb.Update(model);
            return View(model);
        }

        public JsonResult DeletePage(int id)
        {
            var result = PageDb.DeletePage(id);
            var data = new { id, result };
            return Json(data, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region Postion

        public ActionResult PositionList()
        {
            var model = PositionDb.GetAllPosition() ?? new List<ViewPositionDto>();
            return View(model);
        }

        public ActionResult AddPosition()
        {
            ViewBag.PageList = PageDb.GetAll() ?? new List<PageDto>();
            return View();
        }

        [HttpPost]
        public ActionResult AddPosition(PositionDto model)
        {
            model.PositionKey = StringUtil.RemoveSpecialCharactersVn(model.Name).ToUpper();
            var positionList = PositionDb.GetAllByKey(model.PositionKey) ?? new List<PositionDto>();
            if (positionList.Any())
            {
                ModelState.AddModelError("ErrorSummary", "Đã có vị trí với tên này!");
                return View(model);
            }

            model.CreateDate = DateTime.Now;
            var result = PositionDb.AddPosition(model);
            return RedirectToAction("EditPosition", "AdminBanner", new { id = result });
        }

        public ActionResult EditPosition(int id)
        {
            ViewBag.PageList = PageDb.GetAll() ?? new List<PageDto>();
            var model = PositionDb.GetById(id) ?? new PositionDto();
            return View(model);
        }

        [HttpPost]
        public ActionResult EditPosition(PositionDto model)
        {
            model.PositionKey = StringUtil.RemoveSpecialCharactersVn(model.Name).ToUpper();
            var positionList = PositionDb.GetAllByKey(model.PositionKey) ?? new List<PositionDto>();
            if (positionList.Any())
            {
                ModelState.AddModelError("ErrorSummary", "Đã có vị trí với tên này!");
                return View(model);
            }

            PositionDb.Update(model);
            return RedirectToAction("EditPosition", new { id = model.PositionId });
        }

        public JsonResult DeletePosition(int id)
        {
            var result = PositionDb.DeletePosition(id);
            var data = new { id, result };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        #endregion

    }
}
